package com.siecomzg.transport;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.siecomzg.algorithm.sm.SMUtil;
import com.siecomzg.tool.ByteTool;
import com.siecomzg.tool.LogUtil;

import com.google.protobuf.ByteString;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.constconfig.ErrorDefine;
import com.siecomzg.module.EmvOptions;
import com.siecomzg.tool.MD5;
import com.siecomzg.tool.Point;
import com.siecomzg.transport.handler.CommonHandler;
import com.siecomzg.transport.handler.FinanHandler;
import com.siecomzg.transport.handler.FingerPrintHandler;
import com.siecomzg.transport.handler.IdentityHandler;
import com.siecomzg.transport.handler.KeyBoardHandler;
import com.siecomzg.transport.handler.OtherHandler;
import com.siecomzg.transport.handler.SignatureHandler;
import com.siecomzg.transport.handler.UpdateHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.siecomzg.constconfig.ConstDefine.IC_CARD;
import static com.siecomzg.constconfig.ConstDefine.MSR_CARD;
import static com.siecomzg.constconfig.ConstDefine.PIC_CARD;

/**
 * Created  on 2016/7/27.
 */
public class SiecomDevice {

    private static final String TAG = "SiecomDevice";
    public static Distribution distribution = new Distribution();

    private static CallBackHandler handler = new CallBackHandler();
    private static boolean isDebug = true;
    private final static int START = 0;
    private final static int SUCCESS = 1;
    private final static int ERROR = 2;
    private final static int COMPLETED = 3;
    private static ExecutorService executorService = Executors.newFixedThreadPool(5);
    private static Context mContext;
    public static boolean isConnected = false;

    public static enum Result {
        START, SUCCEED, ERROR, COMPLETED

    }

    public static void setIsDebug(boolean debug){
        isDebug = debug;
    }
    public static void testSerial(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.SERIAL_TEST_REQUEST);
                msgBuilder.setRequest("");
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }

    /**
     * 蜂鸣控制
     * @param param times	蜂鸣次数  timeout	蜂鸣持续时间,100毫秒的倍数
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void makeBeep(final String param, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.MAKE_BEEP_REQUEST);
                msgBuilder.setRequest(param);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);
            }
        };
        executorService.execute(r);
    }

    /**
     * 全部熄灭和点亮
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void testLight(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        testLight(callback,timeOutMs,-1,1,isOnMain);
    }

    /**
     * 根据传进来的灯号码控制灯的亮灭
     * @param callback 回调
     * @param timeOutMs 超时
     * @param ledNum 灯号  -1 控制全部
     * @param onOff 0 灭  1 亮
     * @param isOnMain 是否主线程
     */
    public static void testLight(final DeviceCallback callback, final int timeOutMs, final int ledNum,final int onOff, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.LIGHT_TEST_REQUEST);
                msgBuilder.setRequest("" + ledNum);
                msgBuilder.setRespond("" + onOff);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }

    public static void testPsam(final String solt,final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.PSAM_TEST_REQUEST);
                msgBuilder.setRequest(solt);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }
    public static void calcMac(final int mainkey,final int workkey,final int macMode,final String data,final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.CALCMAC_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("mainKeyIndex", mainkey);
                    json.put("workKeyIndex", workkey);
                    json.put("macMode",macMode);
                    json.put("data",data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }
    public static void startLauncher(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.START_LAUNCHER_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }


    public static void resetKeyboard(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.RESET_KEYBOARD_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void updateMainKey(final String keyIndex, final String keyData, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.TMK_OLD_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("keyIndex", keyIndex);
                    json.put("keyData", keyData);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    /**
     * 对数据进行加密或解密
     * @param keyIndex 密钥索引
     * @param keyData 数据 长度小于 4096
     * @param encryptType 加密类型  1 des 2 SM4
     * @param deOrEncrypt  0 加密 1 解密
     * @param enMode  0 ECB  1 CBC
     * @param callback 回调
     * @param timeOutMs 超时
     * @param isOnMain 主密钥
     */
    public static void calculateData(final String keyIndex, final String keyData,final int deOrEncrypt,final int encryptType,
                                     final int enMode,final DeviceCallback callback,
                                         final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.TMK_DECRYPT_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("keyIndex", keyIndex);
                    json.put("keyData", keyData);
                    json.put("encryptType",encryptType);
                    json.put("mode",deOrEncrypt);
                    json.put("enMode",enMode); // 0 ECB   1 CBC
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }



    public static void useKeyBoardInput(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.TMK_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    //检测各个模块状态是否正常
    public static void checkDeviceModuleState(final String modules, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHECK_MODULE_INFO_REQUEST);
                msgBuilder.setRequest(modules);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void resetModule(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.RESET_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void updateFw(final String fileName, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                UpdateHandler.upDateFail = false;
                byte[]  fileByte = readFile(fileName);
                String newFileName = fileName;
                String temp[] = newFileName.split("\\"+File.separator);
                newFileName = temp[temp.length-1];
                LogUtil.e("newFileName",newFileName + "--文件长度：" + fileByte.length);
                if(null==fileByte){
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.NO_FILE);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.NO_FILE));
                    deliverResult(callback, Result.ERROR, bundle, isOnMain);
                    return;
                }
                JSONObject jb = new JSONObject();
                try {
                    jb.put("name",newFileName);
                    jb.put("md5", MD5.getMD5Three(fileName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                com.siecomzg.proto.Message.siecomproto msg;
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.UPDATE_MODULE);
                msgBuilder.setCmd(ConstDefine.UPDATE_FW_REQUEST);

                UpdateHandler handler = (UpdateHandler) HandlerManger.getHandler(ConstDefine.UPDATE_MODULE);

                if(fileName.endsWith("apk") || fileName.endsWith("bin") || fileName.endsWith("zip")){
                    int per = 1024*10;
                    byte[] perByte = new byte[per];
                    int total,lastSize = 0;

                    if(fileByte.length%per ==0){
                        total = fileByte.length/per;
                    }else {
                        total = fileByte.length/per + 1;
                        lastSize = fileByte.length%per;
                    }
                    LogUtil.e(TAG,"总长度：" + fileByte.length + "---最后的长度：" + lastSize + "");

                    ByteString bytes;
                    for (int i=1; i<= total; i++){
//                        if (UpdateHandler.upDateFail){
//                            LogUtil.e(TAG,"UpdateHandler.upDateFailed break" );
//                            break;
//                        }


                        try {
                            jb.put("total",total);
                            jb.put("num",i);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if(lastSize != 0 ){
                            if(i == total){
                                perByte = new byte[lastSize];
                                System.arraycopy(fileByte,(i-1)*per,perByte,0,lastSize);
                            }else {
                                System.arraycopy(fileByte,(i-1)*per,perByte,0,per);
                            }
                        }else {
                            System.arraycopy(fileByte,(i-1)*per,perByte,0,per);
                        }
                        bytes = ByteString.copyFrom(perByte);
                        msgBuilder.setMsgid(getUUID());
                        msgBuilder.setTimeout(timeOutMs);
                        msgBuilder.setRequest(jb.toString());
                        msgBuilder.setExtion(bytes);
                        msg = msgBuilder.build();
                        handler.sendMessage(msg,"", callback, isOnMain);
                        try {
                            if(i==1){
                                Thread.sleep(500);
                            }
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }else { //文件格式错误
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.FILE_ERROR);
                    bundle.putString("message", "文件格式错误");
                    deliverResult(callback, Result.ERROR, bundle, isOnMain);
                }


            }

        };
        executorService.submit(runnable);

    }
    public static byte[] readFile(String fileName){
        byte[] binBuffer = null;
        try{
            FileInputStream fin = new FileInputStream(fileName);
            int availableLen = fin.available();
            LogUtil.i("readFile", "availableLen = " + availableLen);
            binBuffer = new byte[availableLen];
            int iFileLen = fin.read(binBuffer);
            if(iFileLen != availableLen){
                fin.close();
                LogUtil.i("readFile", "readfile failed: ");
                return null;
            }
            LogUtil.i("readFile", "iFileLen: " + iFileLen);
            fin.close();
            fin = null;
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }

        return binBuffer;
    }

    /**
     *
     * @param mainKey 主密钥
     * @param index 索引
     * @param type 类型 1 DES 2 SM4
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void setSignMainKey(final String mainKey, final int index, final int type,
                                      final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                final JSONObject jb = new JSONObject();
                try {
                    jb.put("mainKey",mainKey);
                    jb.put("index",index);
                    jb.put("type",type);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.SIGNATURE_MODULE);
                msgBuilder.setCmd(ConstDefine.SIGNATURE_SM4_REQUEST);
                msgBuilder.setRequest(jb.toString());
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                SignatureHandler handler = (SignatureHandler) HandlerManger.getHandler(ConstDefine.SIGNATURE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }
    //签名用的密钥
    public static void setSM4PrimaryKey(final byte[] sm4key,final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.SIGNATURE_MODULE);
                msgBuilder.setCmd(ConstDefine.SIGNATURE_SM4_REQUEST);
                ByteString sm4ByteString = ByteString.copyFrom(sm4key);
                msgBuilder.setExtion(sm4ByteString);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                SignatureHandler handler = (SignatureHandler) HandlerManger.getHandler(ConstDefine.SIGNATURE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    //签名用到的SM2密钥
    public static void transSM2PublicKey(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.SIGNATURE_MODULE);
                msgBuilder.setCmd(ConstDefine.SIGNATURE_SM2_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                SignatureHandler handler = (SignatureHandler) HandlerManger.getHandler(ConstDefine.SIGNATURE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void getSignature(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        getSignature(callback,timeOutMs,"10",isOnMain);
    }
    public static void getSignature(final DeviceCallback callback, final int timeOutMs, final String  scale, final boolean isOnMain) {
        getSignature(callback,timeOutMs,scale,"",isOnMain);
    }
    /**
     * 获取签名图片和轨迹
     * @param callback
     * @param timeOutMs 超时时间
     * @param scale 压缩比例 1-10；
     * @param jsonParm  width 宽度0 恒定  其他 跟据压感变化
     * @param isOnMain
     */
    public static void getSignature(final DeviceCallback callback, final int timeOutMs, final String  scale, final String jsonParm, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.SIGNATURE_MODULE);
                msgBuilder.setCmd(ConstDefine.SIGNATURE_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                int s = Integer.parseInt(scale);
                JSONObject jb = new JSONObject();
                try {

                    if(s < 0 || s > 10){
                        s = 10;
                    }
                    jb.put("scale",s);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                msgBuilder.setRequest(jb.toString());
                msgBuilder.setRespond(jsonParm); //其他的参数 2022.09.14 新加
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                SignatureHandler handler = (SignatureHandler) HandlerManger.getHandler(ConstDefine.SIGNATURE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }
    public static StringBuffer DisplayTrackData(ArrayList<Point> mArrayList){
        StringBuffer mStringBuffer = new StringBuffer();
        for(int i = 0;i < mArrayList.size();i++){
            Point mPoint = mArrayList.get(i);
            mStringBuffer.append(mPoint.getT()+"{"+mPoint.getX()+","+mPoint.getY()+"}");
        }

        return mStringBuffer;
    }

    public static void cancelCurrentTask(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        final com.siecomzg.proto.Message.siecomproto msg = CallbackMap.getInstance().getCurrentMsg();


        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (msg == null) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.THIS_TASK_IS_FINISH);
                    bundle.putString("message", "THIS_TASK_IS_FINISH");
                    callback.onError(bundle);
                }
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(msg.getModule());
                switch (msg.getModule()) {
                    case ConstDefine.FINAN_MODULE:
                        msgBuilder.setCmd(ConstDefine.CANCEL_FINAN_REQUEST);
                        break;
                    case ConstDefine.FINGE_MODULE:
                        msgBuilder.setCmd(ConstDefine.FINGER_CANCEL_REQUEST);
                        break;
                    case ConstDefine.ID_MODULE:
                        msgBuilder.setCmd(ConstDefine.IDENTITY_CANCEL_REQUEST);
                        break;
                    case ConstDefine.KEY_MODULE:
                        msgBuilder.setCmd(ConstDefine.KEYBOARD_CANCEL_REQUEST);
                        break;
                    case ConstDefine.SIGNATURE_MODULE:
                        msgBuilder.setCmd(ConstDefine.SIGNATURE_CANCEL_REQUEST);
                        break;
                    /**
                     * 其他的非模块任务不能取消
                     */
                    default:
                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.THIS_TASK_NO_CANCEL);
                        bundle.putString("message", "THIS_TASK_NO_CANCEL");
                        deliverResult(callback, Result.ERROR, bundle, isOnMain);
                        return;
                }
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                CommonHandler handler = (CommonHandler) HandlerManger.getHandler(msg.getModule());
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);


    }

    public static void sendToRemote(com.siecomzg.proto.Message.siecomproto msg, String msgStr) throws IOException {

        if(ConstDefine.CONNECT_TYPE == ConstDefine.CONNECT_TYPE_BLUE){
            distribution.mBlueClient.sendToRemote(msg,msgStr);
        }else if(ConstDefine.CONNECT_TYPE == ConstDefine.CONNECT_TYPE_USB){
            distribution.mUsbClient.sendToRemote(msg);
        }
        if (msg.getModule() != ConstDefine.UPDATE_MODULE){
            LogUtil.e(TAG,"connect type=" + ConstDefine.CONNECT_TYPE + "--发送消息：" + msg.toString());
        }
//        LogUtil.e(TAG,"type=" + ConstDefine.CONNECT_TYPE + "--发送消息：" + ByteTool.byte2hex(msg.toByteArray()));
    }

    /**
     * 设置蓝牙名称 重命名
     * @param codeName
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void setBlueName(final String codeName, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CHANGE_BLUE_NAME);
                msgBuilder.setTimeout(timeOutMs);
                msgBuilder.setRequest(codeName);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void setCodeName(final String codeName, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.CODENAME_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                msgBuilder.setRequest(codeName);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void getCodeName(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_CODENAME_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void getDeviceSN(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.DEVICE_SERIAL_NO_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    /**
     * 获取固件版本
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void getDeviceHWVersion(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_DEVICE_VERSION_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void keySetEncryptMode(final int encryptType, final int endType, final int mkeyIndex, final int wkeyIndex, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.SET_ENCRYPT_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("encrypt", encryptType);
                    if(mkeyIndex!=-1) {
                        String mkeyIndexStr = String.format("%02d", mkeyIndex);
                        String wkeyIndexStr = String.format("%02d", wkeyIndex);
                        json.put("mKeyIndex", mkeyIndexStr);
                        json.put("wKeyIndex", wkeyIndexStr);
                    }
                    if(endType!=-1){
                        String endTypeStr = String.format("%02d", endType);
                        json.put("endType",endTypeStr);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    /**
     *
     * @param cardNo 卡号
     * @param mainKeyIndex 索引
     * @param workKeyIndex 密钥索引
     * @param encryptType 加密类型 1 3DES  2 SM4  3 明文
     * @param pwdLength 长度
     * @param passVoice 声音类型
     * @param callback 回调
     * @param timeOutMs 超时
     * @param inputTimes 输入次数 1或2
     * @param isOnMain 主线程
     */
    public static void startInputPwd(final String cardNo, final String mainKeyIndex, final String workKeyIndex,
                                     final int encryptType, final String pwdLength,final int passVoice,
                                     final DeviceCallback callback, final int timeOutMs,final int inputTimes, final boolean isOnMain) {
        if (encryptType != 3 && Integer.parseInt(pwdLength) > 14){
            Bundle bundle = new Bundle();
            bundle.putInt("code", ErrorDefine.LENGTH_ERR);
            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.PWD_LENGTH_ERR));
            deliverResult(callback, Result.ERROR, bundle, isOnMain);
            return;
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.INPUT_KEY_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("cardNo", cardNo);
                    json.put("mainKeyIndex", mainKeyIndex);
                    json.put("workKeyIndex", workKeyIndex);
                    json.put("encryptType", encryptType);
                    json.put("pwdLength", pwdLength);
                    json.put("passVoice",passVoice);
                    json.put("inputTimes",inputTimes);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    /**
     *
     * @param cardNo
     * @param mainKeyIndex
     * @param workKeyIndex
     * @param encryptMode  1 3des   2 sm4  3 明文
     * @param pwdLength
     * @param callback
     * @param timeOutMs
     * @param inputTimes
     * @param isOnMain
     */
    public static void startInputPwd(final String cardNo, final String mainKeyIndex, final String workKeyIndex,
                                     final String encryptMode, final String pwdLength, final DeviceCallback callback,
                                     final int timeOutMs,final int inputTimes, final boolean isOnMain) {
        startInputPwd(cardNo,mainKeyIndex,workKeyIndex,Integer.parseInt(encryptMode),pwdLength,0,callback,timeOutMs,inputTimes,isOnMain);

    }

    /**
     * 获取16位随机数 32个字符
     * @return
     */
    public static String getRandom32(){
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        // 去掉"-"符号
        StringBuffer temp = new StringBuffer();
        temp.append(str.substring(0, 8))
                .append(str.substring(9, 13))
                .append(str.substring(14, 18))
                .append(str.substring(19, 23))
                .append(str.substring(24));
        return temp.toString();
    }

    /**
     * sm2解密数据
     * @param priKey  私钥
     * @param data 要解密的数据
     * @param mode 1 或 2
     * @return
     */
    public static String sm2Decrypt(String priKey,String data,int mode){
        byte[] bytes = SMUtil.SM2PrvDecrypt(priKey,data,mode);
        String result = ByteTool.byte2hex(bytes);
        LogUtil.e(TAG,"解密结果：" + result);
        return result;
    }
    /**
     *  使用传入的公钥加密主密钥 并返回随机主密钥
     * @param keyIndex 密钥索引
     * @param pubKey 传入的公钥数据
     * @param encryptMode   1 c1c2c3    2 c1c3c2
     * @param callback 回调 用bundle.getString("data") 取加密后的数据
     * @param timeOutMs 超时
     * @param isOnMain 是否主线程
     */
    public static void generateProtectKey(final String keyIndex, final String pubKey,final int encryptMode, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Bundle bundle = new Bundle();
        String data = getRandom32();
        if(TextUtils.isEmpty(data)){
            data = getRandom32();
        }
        if (pubKey.length() != 128 && data.length() != 32){
            bundle.putString("message","公钥或加密数据位数不对");
            bundle.putInt("code",-1);
            if(callback != null)
                callback.onError(bundle);
            return;
        }
        String pubX = pubKey.substring(0,64);
        String pubY = pubKey.substring(64);
//        LogUtil.e(TAG,"x="+ pubX + "--y=" + pubY);
        int mode = 1; //mode 1 c1c2c3    2 c1c3c2
        if (encryptMode == 1){
            mode = 1;
        }else{
            mode = 2;
        }
        LogUtil.e(TAG,"mode == " + mode);
        String result = SMUtil.SM2PubEncrypt(ByteTool.hexStr2Bytes(data),pubX,pubY,mode);
        result = result.toUpperCase();
        LogUtil.e(TAG,"加密结果：" + result);

        final String finalResult = result;
        inputMainKey( keyIndex, data,2, 0x00, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                callback.onError(bundle);
            }

            @Override
            public void onSuccess(Bundle bundle) {
                bundle.putString("data", finalResult);
                callback.onSuccess(bundle);
            }

            @Override
            public void onCompleted(Bundle bundle) {
                callback.onCompleted(bundle);
            }
        }, timeOutMs, isOnMain);

    }


        /**
         *
         * @param keyIndex
         * @param keyData
         * @param encryptType  1:3DES；2：SM4
         * @param mode   0x00 明文写入   0x81 解密写入
         * @param callback
         * @param timeOutMs
         * @param isOnMain
         */
    public static void inputMainKey(final String keyIndex, final String keyData,final int encryptType,final int mode, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        if (keyData.length() != 16 && keyData.length() != 32){
            Bundle bundle = new Bundle();
            bundle.putInt("code",ErrorDefine.KEY_INPUT_ERR);
            bundle.putString("message","密钥位数不对");
            callback.onError(bundle);
            return;
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.INPUT_MAIN_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("keyIndex", keyIndex);
                    json.put("keyData", keyData);
                    json.put("encryptType",encryptType);
                    json.put("mode",mode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    //默认 pinKey
    public static void inputWorkKey(final String mainKeyIndex, final String workKeyIndex, final String keyData,
                                    final int encryptType,final int mode, final DeviceCallback callback,
                                    final int timeOutMs, final boolean isOnMain) {
        inputWorkKey(mainKeyIndex,workKeyIndex,keyData,encryptType,mode,1,callback,timeOutMs,isOnMain);
    }
    /**
     *
     * @param mainKeyIndex 0-5
     * @param workKeyIndex 0-5
     * @param keyData 数据
     * @param encryptType 1:3DES；2：SM4
     * @param mode  0x00明文写入  0x81 解密写入  0x01加密写入
     * @param keyType 1 计算pin  2 mac  3 加解密数据
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void inputWorkKey(final String mainKeyIndex, final String workKeyIndex, final String keyData,
                                    final int encryptType,final int mode,final int keyType, final DeviceCallback callback,
                                    final int timeOutMs, final boolean isOnMain) {

        if (keyData.length() != 16 && keyData.length() != 32){
            Bundle bundle = new Bundle();
            bundle.putInt("code",ErrorDefine.KEY_INPUT_ERR);
            bundle.putString("message","密钥位数不对");
            callback.onError(bundle);
            return;
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.INPUT_WORK_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("mainKeyIndex", mainKeyIndex);
                    json.put("workKeyIndex", workKeyIndex);
                    json.put("keyData", keyData);
                    json.put("encryptType",encryptType);
                    json.put("mode",mode);
                    json.put("keyType",keyType);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }


    /**
     * 设置通讯密钥
     * @param keyData 密钥数据
     * @param keyType 密钥类型 国际国密
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void setCommuKey(final String keyData,final int keyType, final DeviceCallback callback,
                                    final int timeOutMs, final boolean isOnMain) {

        if (keyData.length() != 16 && keyData.length() != 32){
            Bundle bundle = new Bundle();
            bundle.putInt("code",ErrorDefine.KEY_INPUT_ERR);
            bundle.putString("message","密钥位数不对");
            callback.onError(bundle);
            return;
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.INPUT_COMMU_KEY_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("keyData", keyData);
                    json.put("keyType",keyType);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    /**
     *国际或国密的方式 用传入的公钥加密随机生成的主密钥 并返回加密后的主密钥
     * @param mainKeyIndex 密钥索引
     * @param pubKeyType 公钥类型 0--RSA， 1--SM2
     * @param sessionKeyType 生成的会话密钥类型 1——DES 单倍长 2 —— DES 双倍长 3—— DES 三倍长  4 —— SM4
     * @param pubkeyData 公钥 数据
     * @param callback 回调
     * @param timeOutMs 超时
     * @param isOnMain 是否主线程
     */
    public static void sm2OrDesGetMainKey(final int mainKeyIndex,final int pubKeyType,final int sessionKeyType,
                                          final String pubkeyData,
                                          final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.KEY_MODULE);
                msgBuilder.setCmd(ConstDefine.SM2_RSA_MAINKEY_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                JSONObject json = new JSONObject();
                try {
                    json.put("mainKeyIndex", mainKeyIndex);
                    json.put("pubKeyType", pubKeyType);
                    json.put("pubKeyData", pubkeyData);
                    json.put("sessionKeyType",sessionKeyType);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(json.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                KeyBoardHandler handler = (KeyBoardHandler) HandlerManger.getHandler(ConstDefine.KEY_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void getTemplet(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.TEMPLET_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void matchFinger(final String feature,final String templet,final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.MATCH_REQUEST);
                msgBuilder.setTimeout(timeOutMs);

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("feature", feature);
                    jsonObject.put("templet", templet);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void readFingerVersion(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.FINGER_VER_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    public static void readFingerPic(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.FINGER_PIC_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void fingerRegist(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.FINGER_REGIST_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void readFingerFeature(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        readFingerFeature(callback,timeOutMs,false,isOnMain);
    }
    public static void readFingerFeature(final DeviceCallback callback, final int timeOutMs,boolean withImg, final boolean isOnMain) {

        final JSONObject jb = new JSONObject();
        try {
            jb.put("withImg",withImg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.FINGERFEARURE_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                msgBuilder.setRespond(jb.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }
    public static void readFingerTempleteRegist(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        final JSONObject jb = new JSONObject();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINGE_MODULE);
                msgBuilder.setCmd(ConstDefine.FINGER_REGIST_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                msgBuilder.setRespond(jb.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FingerPrintHandler handler = (FingerPrintHandler) HandlerManger.getHandler(ConstDefine.FINGE_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);

    }

    // todo----- 银行卡---------------------------------------------------------------------------------------------------------------

    /**
     *
     * @param cardType  IC 卡类型，0 接触，1 非接  2 自动 底座会根据插卡类型自动检测上电
     * @param callback
     * @param timeoutMs
     * @param isOnMain
     */
    public static void iccPowerOn(final int cardType,final DeviceCallback callback,final int timeoutMs,final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.ICCard_POWER_ON_REQUEST);
                LogUtil.e("cardType", cardType + "==");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("cardType", cardType);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setTimeout(timeoutMs);
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }
    public static void iccPowerOff(final int cardType,final DeviceCallback callback,final int timeoutMs,final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.ICCard_POWER_OFF_REQUEST);
                LogUtil.e("cardType", cardType + "==");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("cardType", cardType);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setTimeout(timeoutMs);
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void icApdu(final int cardType, final String dataIn, final DeviceCallback callback, final int timeoutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.APDU_COMMAND_REQUEST);
                LogUtil.e("cardType", cardType + "==");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("cardType", cardType);
                    jsonObject.put("apdu",dataIn);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setTimeout(timeoutMs);
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    /**
     * 读社保卡
     * @param cardType
     * @param dataIn
     * @param callback
     * @param timeoutMs
     * @param isOnMain
     */
    public static void readSocialCard(final int cardType, final String dataIn, final DeviceCallback callback, final int timeoutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.READ_SOCIAL_CARD_REQUEST);
                LogUtil.e("cardType", cardType + "==");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("cardType", cardType);
                    jsonObject.put("apdu",dataIn);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setTimeout(timeoutMs);
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void ARPCExecuteScript(final int cardType, final String arpc, final String script, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.ARQC_REQUEST);
                LogUtil.e("cardType", cardType + "==");
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("cardType", cardType);
                    jsonObject.put("arpc", arpc);  //包含了ARPC和脚本
                    jsonObject.put("script", script); //strTxData
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setTimeout(timeOutMs);
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);


    }
    public static void readLoadLog(final int cardType, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                if (cardType == ConstDefine.PIC_CARD) {
                    msgBuilder.setCmd(ConstDefine.PIC_LOAD_REQUEST);
                } else if(cardType == ConstDefine.IC_CARD){
                    msgBuilder.setCmd(ConstDefine.IC_LOAD_REQUEST);
                }else{
                    msgBuilder.setCmd(ConstDefine.AUTO_LOAD_REQUEST);
                }
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }

    public static void readTradeLog(final int cardType, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                if (cardType == ConstDefine.PIC_CARD) {
                    msgBuilder.setCmd(ConstDefine.PIC_LOG_REQUEST);
//                    msgBuilder.setCmd(ConstDefine.PIC_LOAD_REQUEST); //圈存交易日志
                } else if(cardType == ConstDefine.IC_CARD) {
                    msgBuilder.setCmd(ConstDefine.IC_LOG_REQUEST);
//                    msgBuilder.setCmd(ConstDefine.IC_LOAD_REQUEST); //圈存交易日志
                }else{
                    msgBuilder.setCmd(ConstDefine.AUTO_LOG_REQUEST);
                }
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);


            }
        };
        executorService.execute(r);

    }

    public static void readBankCard(final int cardType, final DeviceCallback callback, final EmvOptions options,final String[] wantTags,final int timeOutMs, final boolean isOnMain) {
        JSONObject inJson = new JSONObject();
        try {
            inJson.put("voiceType",2); //
            inJson.put("wKeyIndex","");
            inJson.put("encryptType",0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        readBankCard(cardType,callback,options,wantTags,inJson.toString(),timeOutMs,isOnMain);
    }

    public static void readBankCard(final int cardType, final DeviceCallback callback, final EmvOptions options, final String[] wantTags, final String inJsonParm, final int timeOutMs, final boolean isOnMain) {


        Runnable r = new Runnable() {
            @Override
            public void run() {
                int cmd = 0;
                switch (cardType) {
                    case IC_CARD:
                        cmd = ConstDefine.IC_REQUEST;
                        break;
                    case PIC_CARD:
                        cmd = ConstDefine.PIC_REQUEST;
                        break;
                    case MSR_CARD:
                        cmd = ConstDefine.MSR_REQUEST;
                        break;
                    default:
                        cmd = ConstDefine.AUTO_REQUEST;
                        break;

                }
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(cmd);
                msgBuilder.setTimeout(timeOutMs);
                if(options != null){
                    if (options.getEmvParam() != null){
                        LogUtil.e(TAG,"EMvParam String==" + ByteTool.byte2hex(options.getEmvParam().toBytes()));
                        ByteString emvParamByteString = ByteString.copyFrom(options.getEmvParam().toBytes());
                        msgBuilder.setExtion(emvParamByteString);
                    }

                }

                JSONObject jsonObject = new JSONObject();
                try {
                    if(wantTags!=null) {
                        JSONArray jsonArray = new JSONArray();
                        for (int i = 0; i < wantTags.length; i++) {
                            jsonArray.put(wantTags[i]);
                        }
                        jsonObject.put("wantTags",jsonArray);
                    }
                    if(options != null){
                        jsonObject.put("time", options.getTime());
                        jsonObject.put("TransNo", options.getTransNo());
                        jsonObject.put("authorizedAmount", options.getAuthorizedAmount());
                    }
                    JSONObject inJson = new JSONObject(inJsonParm);
                    jsonObject.put("wKeyIndex",inJson.optString("wKeyIndex"));
                    jsonObject.put("encryptType",inJson.optString("encryptType"));
                    jsonObject.put("voiceType",inJson.optString("voiceType"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.execute(r);

    }
    // 自动检测卡类型 如果为磁条卡 返回磁道数据
    public static void readCheckCard(final int cardType, final DeviceCallback callback, final EmvOptions options, final String[] wantTags, final String inJsonParm, final int timeOutMs, final boolean isOnMain) {


        Runnable r = new Runnable() {
            @Override
            public void run() {

                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.FINAN_MODULE);
                msgBuilder.setCmd(ConstDefine.AUTO_CHECK_REQUEST);
                msgBuilder.setTimeout(timeOutMs);


                JSONObject jsonObject = new JSONObject();
                try {
                    if(wantTags!=null) {
                        JSONArray jsonArray = new JSONArray();
                        for (int i = 0; i < wantTags.length; i++) {
                            jsonArray.put(wantTags[i]);
                        }
                        jsonObject.put("wantTags",jsonArray);
                    }
                    if(options != null){
                        jsonObject.put("time", options.getTime());
                        jsonObject.put("TransNo", options.getTransNo());
                        jsonObject.put("authorizedAmount", options.getAuthorizedAmount());
                    }
                    if (!TextUtils.isEmpty(inJsonParm)){
                        JSONObject inJson = new JSONObject(inJsonParm);
                        jsonObject.put("wKeyIndex",inJson.optString("wKeyIndex"));
                        jsonObject.put("encryptType",inJson.optString("encryptType"));
                        jsonObject.put("voiceType",inJson.optString("voiceType"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                msgBuilder.setRequest(jsonObject.toString());
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                FinanHandler handler = (FinanHandler) HandlerManger.getHandler(ConstDefine.FINAN_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.execute(r);

    }

    // todo----- 身份证 ---------------------------------------------------------------------------------------------------------------
    public static void readIdentityCard(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        readIdentityCard(callback,timeOutMs,2,isOnMain);
    }

    /**
     *
     * @param callback
     * @param timeOutMs
     * @param orgData 是否 要原始数据 1  要  2 不要
     * @param isOnMain
     */
    public static void readIdentityCard(final DeviceCallback callback, final int timeOutMs, final int orgData, final boolean isOnMain) {

        Runnable r = new Runnable() {
            @Override
            public void run() {

                JSONObject jb = new JSONObject();
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                try {

                    msgBuilder.setMsgid(getUUID());
                    msgBuilder.setModule(ConstDefine.ID_MODULE);
                    msgBuilder.setCmd(ConstDefine.ID_READ_REQUEST);
                    msgBuilder.setTimeout(timeOutMs);
                    jb.put("orgData",orgData);
                    msgBuilder.setRequest(jb.toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                IdentityHandler handler = (IdentityHandler) HandlerManger.getHandler(ConstDefine.ID_MODULE);
                handler.sendMessage(msg,jb.toString(), callback, isOnMain);


            }
        };
        executorService.execute(r);


    }

    /**
     * 获取电池信息
     * @param callback
     * @param timeOutMs
     * @param isOnMain
     */
    public static void getBattaryInfo(final DeviceCallback callback, final int timeOutMs, final boolean isOnMain){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.GET_BATTARY_INFO_REQUEST);
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);

            }
        };
        executorService.submit(runnable);
    }

    public static void connectStatusChange(ConnectStatusCallback callback) {
        if (distribution != null) {
            distribution.setConnectStatusCallback(callback);
        }

    }


    public static void setContext(Context context){
        mContext = context;
    }
    
    public static void startConnect(final BluetoothDevice device, final DeviceCallback callback, final boolean isOnMain) {
        InitializeBluetoochAdapter();
        new Thread(new Runnable() {
            @Override
            public void run() {
                deliverResult(callback, Result.START, null, isOnMain);
                try {
                    distribution.init(device);
                    distribution.startListen();
                    Bundle bundle = new Bundle();
                    deliverResult(callback, Result.SUCCEED, bundle, isOnMain);
                    isConnected = true;
                    LogUtil.e(TAG,"startConnect ----- conn == " + isConnected);
                    ConstDefine.CONNECT_TYPE = ConstDefine.CONNECT_TYPE_BLUE; //蓝牙连接
                } catch (IOException e) {
                    e.printStackTrace();
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.UNKNOW_ERROR);
                    bundle.putString("message", e.getMessage());
                    deliverResult(callback, Result.ERROR, bundle, isOnMain);
                } finally {
                    deliverResult(callback, Result.COMPLETED, new Bundle(), isOnMain);
                }

            }
        }).start();

    }

    /**
     * 断开蓝牙连接
     */
    public static void disConnect(final DeviceCallback callback,final boolean isOnMain){
        isConnected = false;
        LogUtil.e(TAG, "blue disConnect ---- conn == false" );
        if (mContext != null && mBbluetoothReceive != null)
            mContext.unregisterReceiver(mBbluetoothReceive);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();

                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.DISCONNECT_BLUE);

                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();
                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);
                try {
                    Thread.sleep(100);
                    distribution.stop();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        executorService.submit(runnable);

//        distribution.stop();
    }

    private static class BluetoothReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            LogUtil.e(TAG,"蓝牙状态是："+action);
            switch (action){
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.e(TAG, "TURNING_ON--");
                            break;
                        case BluetoothAdapter.STATE_ON:

                            Log.e(TAG, "STATE_ON--");
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.e(TAG, "STATE_TURNING_OFF-- conn == false");
                            isConnected = false;
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            isConnected = false;
                            Log.e(TAG, "STATE_OFF--");
                            break;
                    }
                    break;
                case "android.bluetooth.BluetoothAdapter.STATE_ON":
                    LogUtil.e(TAG,"STATE_ON---- ");
                    break;

                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    LogUtil.e(TAG,"ACTION_BOND_STATE_CHANGED---- ");
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    LogUtil.e(TAG,"ACTION_DISCOVERY_FINISHED---- ");

                    break;
                case BluetoothDevice.ACTION_ACL_CONNECTED:
                    isConnected = true;
                    LogUtil.e(TAG,"ACTION_ACL_CONNECTED2222---- " + isConnected);
                    break;

                case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                    LogUtil.e(TAG,"ACTION_ACL_DISCONNECTED2222---- " + isConnected);
                    isConnected = false;
                    break;
            }

        }
    }

    private static BluetoothReciever mBbluetoothReceive = null;
    private static void InitializeBluetoochAdapter() {
        mBbluetoothReceive = new BluetoothReciever();
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("android.bluetooth.device.action.FOUND");
        localIntentFilter
                .addAction("android.bluetooth.device.action.BOND_STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.SCAN_MODE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.STATE_CHANGED");
        localIntentFilter
                .addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_STARTED");
        localIntentFilter
                .addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        localIntentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        localIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        localIntentFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        localIntentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");

        if (mContext != null)
            mContext.registerReceiver(mBbluetoothReceive, localIntentFilter);

    }

    public static void makeVoice(final int type, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                com.siecomzg.proto.Message.siecomproto.Builder msgBuilder = com.siecomzg.proto.Message.siecomproto.newBuilder();
                msgBuilder.setMsgid(getUUID());
                msgBuilder.setModule(ConstDefine.OTHER_MODULE);
                msgBuilder.setCmd(ConstDefine.MAKE_VOICE_REQUEST);
                msgBuilder.setRequest(String.valueOf(type));
                msgBuilder.setTimeout(timeOutMs);
                com.siecomzg.proto.Message.siecomproto msg = msgBuilder.build();

                OtherHandler handler = (OtherHandler) HandlerManger.getHandler(ConstDefine.OTHER_MODULE);
                handler.sendMessage(msg,"", callback, isOnMain);
            }
        };
        executorService.execute(r);
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        // 去掉"-"符号
        StringBuffer temp = new StringBuffer();
        temp.append(str.substring(0, 8))
//                .append(str.substring(9, 13))
//                .append(str.substring(14, 18))
//                .append(str.substring(19, 23))
//                .append(str.substring(24))
        ;
        return temp.toString();
    }

    public static synchronized void deliverResult(final DeviceCallback callback, Result result, Bundle bundle, boolean onMainThread) {
        if (onMainThread) {
            handler.setCallback(callback);
            if (result == Result.SUCCEED) {
                Message msg = new Message();
                msg.what = SUCCESS;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.ERROR) {
                Message msg = new Message();
                msg.what = ERROR;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.COMPLETED) {
                Message msg = new Message();
                msg.what = COMPLETED;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.START) {
                Message msg = new Message();
                msg.what = START;
                handler.sendMessage(msg);
            }
        } else {
            if (result == Result.SUCCEED) {
                callback.onSuccess(bundle);
            } else if (result == Result.ERROR) {
                callback.onError(bundle);
            } else if (result == Result.COMPLETED) {
                callback.onCompleted(bundle);
            } else if (result == Result.START) {
                callback.onStart();
            }
        }

    }

    private static class CallBackHandler extends Handler {
        private DeviceCallback callback;

        public CallBackHandler() {
            super(Looper.getMainLooper());

        }

        public void setCallback(DeviceCallback callback) {
            this.callback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START: {
                    callback.onStart();
                    break;
                }
                case SUCCESS: {
                    Bundle bundle = msg.getData();
                    callback.onSuccess(bundle);
                    break;
                }
                case ERROR: {
                    Bundle bundle = msg.getData();
                    callback.onError(bundle);
                    break;
                }
                case COMPLETED: {
                    Bundle bundle = msg.getData();
                    callback.onCompleted(bundle);
                    break;
                }
            }

        }

    }




}
